import fs from 'node:fs';
import readline from 'node:readline';

function getFib() {
  const ri = readline.createInterface({
    crlfDelay: Infinity,
    input: fs.createReadStream(
      'D:/exp-data/ibdiagnet2/ibdiagnet2/ibdiagnet2.far',
    ),
  });
  const fibs = {};
  let groups = {};
  let currSw = '';
  ri.on('line', (line) => {
    const items = line.split(/\s+/);
    if (items[0] === 'Switch') {
      currSw = items[1].slice(2);
      fibs[currSw] = {};
      groups = {};
    } else if (items[0].startsWith('0x')) {
      const match = Number.parseInt(items[0]);
      const action = groups[items[3]];
      fibs[currSw][match] = action;
    } else if (!Number.isNaN(Number.parseInt(items[0]))) {
      groups[items[0]] =
        items.length === 3 ? [] : items[3].split(',').slice(0, -1);
    }
  });
  ri.on('close', () => {
    // fs.writeFileSync('output.json', JSON.stringify(fibs, null, 4));
    // console.log(fibs);
    console.log(Object.keys(fibs).length);
  });
  return fibs;
  // console.log(ns, t);
}
const fibs = getFib();

export default eventHandler(async (event) => {
  console.log(getQuery(event));
  const guid = getQuery(event).id;
  return useResponseSuccess(fibs[guid]);
});
